package com.kingint.web.portal.serve.service.impl;

import com.kingint.mbg.ser.entity.SerCheckRoom;
import com.kingint.mbg.ser.entity.SerReceiveWorkMiddle;
import com.kingint.mbg.ser.entity.SerWorkOrder;
import com.kingint.mbg.ser.mapper.SerCheckRoomMapper;
import com.kingint.mbg.ser.mapper.SerReceiveWorkMiddleMapper;
import com.kingint.mbg.ser.mapper.SerWorkOrderMapper;
import com.kingint.mbg.sys.entity.UmsMember;
import com.kingint.web.admin.base.service.BasOrderTypeHotelTimeService;
import com.kingint.web.portal.base.service.WorkOrderTypeService;
import com.kingint.web.portal.data.service.DataWorkOrderService;
import com.kingint.web.portal.serve.service.ActivitiCancelService;
import com.kingint.web.portal.serve.service.CheckRoomService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kingint.web.sys.service.UmsAdminService;
import com.kingint.web.sys.service.UmsMemberService;
import com.kingint.web.util.CharUtil;
import com.kingint.web.util.WorkType;
import com.kingint.web.util.WorkTypeUtil;
import com.kingint.web.vo.CheckRoomBean;
import com.kingint.web.vo.CountParam;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 查房工单详情表 服务实现类
 * </p>
 *
 * @author wxh
 * @since 2020-12-24
 */
@Slf4j
@Service
public class CheckRoomServiceImpl extends ServiceImpl<SerCheckRoomMapper, SerCheckRoom> implements CheckRoomService {

    @Resource
    private UmsAdminService adminService;
    @Resource
    private UmsMemberService umsMemberService;
    @Resource
    private SerWorkOrderMapper workOrderMapper;
    @Resource
    private SerReceiveWorkMiddleMapper serReceiveWorkMiddleMapper;
    @Resource
    private SerCheckRoomMapper serCheckRoomMapper;
    @Resource
    private ActivitiCancelService activitiCancelService;
    @Resource
    private TaskService taskService;
    @Resource
    private HistoryService historyService;
    @Resource
    private WorkOrderTypeService workOrderTypeService;
    @Resource
    private BasOrderTypeHotelTimeService basOrderTypeHotelTimeService;
    @Resource
    private DataWorkOrderService dataWorkOrderService;

    private String repairInstanceKey = CheckRoomBean.PROCESSINSTANCEKEY;

    /**
     * 创建并完成查房工单
     *
     * @param serCheckRoom
     * @return
     */
    @Override
    public boolean addCheckRoomOder(SerCheckRoom serCheckRoom) {
        UmsMember currentMember = adminService.getCurrentMember();//当前用户
        //添加总工单信息
        SerWorkOrder serWorkOrder = new SerWorkOrder();
        BeanUtils.copyProperties(serCheckRoom, serWorkOrder);
        serWorkOrder.setRoomId(serCheckRoom.getRoomId());
        serWorkOrder.setSubmitUserId(currentMember.getId());//提交人员
        serWorkOrder.setCreateTime(new Date());
        serWorkOrder.setWorkOrderStatus(0);
        serWorkOrder.setOrderStatus(5);
        serWorkOrder.setHotelId(currentMember.getHotelId());
        serWorkOrder.setSubmitUserId(currentMember.getId());
        serWorkOrder.setRoomNum(serCheckRoom.getRoomNum());
        serWorkOrder.setOrderSn(CharUtil.generateOrderSn()); //工单号
        serWorkOrder.setWorkTypeId(WorkTypeUtil.getWorkTypeIdByName(WorkType.checkRoomName)); //工单类型
        //存入总工单
        int insert = workOrderMapper.insert(serWorkOrder);
        SerReceiveWorkMiddle receiveWorkMiddle = new SerReceiveWorkMiddle();
        receiveWorkMiddle.setReceiveUserId(currentMember.getId());
        receiveWorkMiddle.setWorkId(serWorkOrder.getId());
        receiveWorkMiddle.setCreateTime(new Date());
        int insert2 = serReceiveWorkMiddleMapper.insert(receiveWorkMiddle);
        String businessKey = "";
        if (insert > 0) {
            businessKey = CheckRoomBean.PROCESSINSTANCEKEY + "_" + currentMember.getHotelId() + "_" + serWorkOrder.getId();

            //创建查房表信息
            serCheckRoom.setWorkId(serWorkOrder.getId());
            int insert1 = serCheckRoomMapper.insert(serCheckRoom);
            if (insert1 > 0) {
                HashMap<String, Object> checkroomuser = new HashMap<>();
                checkroomuser.put(CheckRoomBean.CHECKPEOPLE, currentMember.getUsername());
                String processInstanceId = activitiCancelService.startProcess(CheckRoomBean.PROCESSINSTANCEKEY, businessKey, checkroomuser);
                Task task = taskService.createTaskQuery()
                        .processDefinitionKey(repairInstanceKey)
                        .processInstanceBusinessKey(businessKey)
                        .singleResult();
                //结束流程-创建节点
                taskService.complete(task.getId());
                Task task1 = taskService.createTaskQuery()
                        .processDefinitionKey(repairInstanceKey)
                        .processInstanceBusinessKey(businessKey)
                        .singleResult();
//                    结束流程-查房节点
                taskService.complete(task1.getId());
                serWorkOrder.setProcessInstanceId(processInstanceId);
                int i = workOrderMapper.updateById(serWorkOrder);
                //工单时间写入redis
                basOrderTypeHotelTimeService.addtim(currentMember.getHotelId(),serWorkOrder.getId(),WorkType.checkRoomName,new Date().getTime());
                //工单写入redis统计h数据
                dataWorkOrderService.addwork(currentMember.getHotelId(), CountParam.CHECKROOMCOUNT);
                return true;
            }

        }
        return false;
    }


    @Override
    public List<SerCheckRoom> getCheckRoomOder() {

        return null;
    }

    @Override
    public boolean complete(SerCheckRoom serCheckRoom) {
        UmsMember currentMember = adminService.getCurrentMember();//当前用户
        String businessKey = CheckRoomBean.PROCESSINSTANCEKEY + "_" + currentMember.getHotelId() + "_" + serCheckRoom.getWorkId();
        //查询运行时的信息
        Task task = taskService.createTaskQuery()
                .processDefinitionKey(CheckRoomBean.PROCESSINSTANCEKEY)
                .processInstanceBusinessKey(businessKey)
                .singleResult();
        //结束流程
        taskService.complete(task.getId());
        SerWorkOrder serWorkOrder = workOrderMapper.selectById(serCheckRoom.getWorkId());
        serWorkOrder.setEndTime(new Date());
        int i = workOrderMapper.updateById(serWorkOrder);
        //删除redis中存储的信息
        basOrderTypeHotelTimeService.deltim(currentMember.getHotelId(),serCheckRoom.getWorkId(),WorkType.checkRoomName);

        return i > 0 ? true : false;
    }

    @Override
    public SerCheckRoom getonebyid(Integer id) {
        SerCheckRoom serCheckRoom = serCheckRoomMapper.selectById(id);
        SerWorkOrder serWorkOrder = workOrderMapper.selectById(serCheckRoom.getWorkId());
        serCheckRoom.setSerWorkOrder(serWorkOrder);
        return serCheckRoom;
    }

    /**
     * 接受查房工单（后台创建，前端接受时使用）
     *
     * @param id 总工单id
     * @return
     */
    @Override
    public boolean acceptCheckRoomOder(Integer id) {  //sercheckroom全部返回
        UmsMember currentMember = adminService.getCurrentMember();//当前用户
        SerWorkOrder serWorkOrder = new SerWorkOrder();
        serWorkOrder.setOrderStatus(2); //更新状态
        serWorkOrder.setStartTime(new Date());//开始处理时间
        workOrderMapper.updateById(serWorkOrder); //更新总表

        String businessKey = CheckRoomBean.PROCESSINSTANCEKEY + "_" + currentMember.getHotelId() + "_" + id;
        Task task = taskService.createTaskQuery()
                .processDefinitionKey(CheckRoomBean.PROCESSINSTANCEKEY)
                .processInstanceBusinessKey(businessKey)
                .singleResult();
        //结束流程
        taskService.complete(task.getId());
        return true;
    }


    /**
     * 完成查房工单（后台创建，前端接受时使用）
     *
     * @param serCheckRoom
     * @return
     */
    @Override
    public boolean completeCheckRoomOder(SerCheckRoom serCheckRoom) {  //sercheckroom全部返回
        UmsMember currentMember = adminService.getCurrentMember();//当前用户
        SerWorkOrder serWorkOrder = new SerWorkOrder();
        BeanUtils.copyProperties(serCheckRoom, serWorkOrder);
        serWorkOrder.setCreateTime(new Date());
        serWorkOrder.setWorkOrderStatus(0);
        serWorkOrder.setOrderStatus(5);
        serWorkOrder.setEndTime(new Date());//完成时间
        serWorkOrder.setId(serCheckRoom.getWorkId()); //回传的总工单id

        workOrderTypeService.judgeWorkOrderIsTimeOut(currentMember.getId(),serCheckRoom.getWorkId(), WorkType.checkRoomName);
//        SerReceiveWorkMiddle receiveWorkMiddle = new SerReceiveWorkMiddle();
//        receiveWorkMiddle.setReceiveUserId(currentMember.getId());
//        receiveWorkMiddle.setWorkId(serWorkOrder.getId());
//        receiveWorkMiddle.setCreateTime(new Date());


        serCheckRoom.setCreateTime(new Date());
        serCheckRoomMapper.updateById(serCheckRoom); //更新查房详情表
        workOrderMapper.updateById(serWorkOrder); //更新总表
//        serReceiveWorkMiddleMapper.insert(receiveWorkMiddle); //更新中间表


        String businessKey = CheckRoomBean.PROCESSINSTANCEKEY + "_" + currentMember.getHotelId() + "_" + serCheckRoom.getWorkId();
        //查询运行时的信息
        Task task = taskService.createTaskQuery()
                .processDefinitionKey(CheckRoomBean.PROCESSINSTANCEKEY)
                .processInstanceBusinessKey(businessKey)
                .singleResult();
        //结束流程
        taskService.complete(task.getId());
        //删除redis中存储的信息
        basOrderTypeHotelTimeService.deltim(currentMember.getHotelId(),serCheckRoom.getWorkId(),WorkType.checkRoomName);
        return true;
    }

    @Override
    public Integer insertCheckRoomInfo(SerCheckRoom serCheckRoom) {
        UmsMember currentMember = adminService.getCurrentMember();//当前用户
        //添加总工单信息
        SerWorkOrder serWorkOrder = new SerWorkOrder();
        BeanUtils.copyProperties(serCheckRoom, serWorkOrder);
        serWorkOrder.setRoomId(serCheckRoom.getRoomId());
        serWorkOrder.setSubmitUserId(currentMember.getId());//提交人员
        serWorkOrder.setCreateTime(new Date());
        serWorkOrder.setWorkOrderStatus(0);
        serWorkOrder.setOrderStatus(2);//处理中
        serWorkOrder.setHotelId(currentMember.getHotelId());
        serWorkOrder.setOrderSn(CharUtil.generateOrderSn()); //工单号
        serWorkOrder.setWorkTypeId(WorkTypeUtil.getWorkTypeIdByName(WorkType.checkRoomName)); //工单类型
        //存入总工单
        int insert = workOrderMapper.insert(serWorkOrder);
        SerReceiveWorkMiddle receiveWorkMiddle = new SerReceiveWorkMiddle();
        receiveWorkMiddle.setReceiveUserId(currentMember.getId());
        receiveWorkMiddle.setWorkId(serWorkOrder.getId());
        receiveWorkMiddle.setCreateTime(new Date());
        serReceiveWorkMiddleMapper.insert(receiveWorkMiddle);
        String businessKey = "";
        if (insert > 0) {
            businessKey = CheckRoomBean.PROCESSINSTANCEKEY + "_" + currentMember.getHotelId() + "_" + serWorkOrder.getId();
            //创建查房表信息
            serCheckRoom.setWorkId(serWorkOrder.getId());
            int insert1 = serCheckRoomMapper.insert(serCheckRoom);
            if (insert1 > 0) {
                HashMap<String, Object> checkroomuser = new HashMap<>();
                checkroomuser.put(CheckRoomBean.CHECKPEOPLE, currentMember.getUsername());
                String processInstanceId = activitiCancelService.startProcess(CheckRoomBean.PROCESSINSTANCEKEY, businessKey, checkroomuser);
                Task task = taskService.createTaskQuery()
                        .processDefinitionKey(repairInstanceKey)
                        .processInstanceBusinessKey(businessKey)
                        .singleResult();
                //结束流程-创建节点
                taskService.complete(task.getId());

                serWorkOrder.setProcessInstanceId(processInstanceId);
                workOrderMapper.updateById(serWorkOrder);
            }
        }
        return serWorkOrder.getId();
    }
}
